<script setup>

import {onMounted, ref} from "vue";
import {doGet, doPost, doPut} from "../../util/request.js";
import {showMessage} from "../../util/message.js";
import {useRoute, useRouter} from "vue-router";

const activity = ref({})

const router = useRouter()
const route = useRoute()

const formRules = {
  name: [
    {required: true, message: '请输入活动名称', trigger: 'blur'},
    {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
  ],
  cost: [
    {required: true, message: '请输入活动预算', trigger: 'blur'},
    {pattern: /^\d+(\.\d{1,2})?$/, message: '请输正确的预算金额',trigger: 'blur'}
  ],
   activityTime: [
       {required: true, message: '请选择活动时间', trigger: 'change'}
   ],
  description: [
    {required: true, message: '请输入活动描述', trigger: 'blur'},
    {min: 3, max: 255, message: '长度在 3 到 255 个字符', trigger: 'blur'}
  ],
}
// 表单提交时验证对象
const ruleFormRef = ref()
// 提交表单
const submit = (formEl) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      let activityId = route.params.id
      // 活动开始时间
      let startTime = ''
      // 活动结束时间
      let endTime = ''
      for (let key in activity.value.activityTime) {
        if (key === '0') {
          startTime = activity.value.activityTime[key]
        }
        if (key === '1') {
          endTime = activity.value.activityTime[key]
        }
      }
      console.log('活动开始时间', startTime)
      console.log('活动结束时间', endTime)
      // 准备参数
      let params = {
        id: activityId,
        name: activity.value.name,
        cost: activity.value.cost,
        description: activity.value.description,
        startTime: startTime,
        endTime: endTime
      }

      console.log('活动信息',params)

      if (activityId) {
        doPut('/api/activity',params)
            .then(resp => {
              if (resp.data.code === 200) {
                showMessage("编辑市场活动成功", 'success');
                // 跳转至列表页面
                window.location.href = '/dashboard/activity';
              } else {
                showMessage("编辑市场活动失败，原因："+resp.data.msg,'error')
              }
            });
      } else {
        // 发起请求
        doPost('/api/activity',params)
            .then(resp => {
              if (resp.data.code === 200) {
                showMessage("新增市场活动成功", 'success');
                // 跳转至列表页面
                window.location.href = '/dashboard/activity';
              } else {
                showMessage("新增市场活动失败，原因："+resp.data.msg,'error')
              }
            });
      }

    }
  })
}

// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

// 查询活动详情信息
const loadActivityDetailInfo = (activityId) => {
  doGet('/api/activity/info/'+activityId,{})
      .then(resp => {
        if (resp.data.code === 200) {
          activity.value = resp.data.data
          activity.value.activityTime = [activity.value.startTime,activity.value.endTime]
        }
      })
}

onMounted(()=>{
  // 获取路由参数活动标识
  let activityId = route.params.id
  if (!activityId) return
  // 加载活动详情信息
  loadActivityDetailInfo(activityId)
})
</script>

<template>
  <h1 v-if="activity.id">编辑市场活动</h1>
  <h1 v-else>新增市场活动</h1>

  <el-form
      ref="ruleFormRef"
      style="max-width: 600px;"
      :model="activity"
      :rules="formRules"
      label-width="auto"
      class="demo-ruleForm">

    <el-form-item label="活动名称" prop="name">
      <el-input v-model="activity.name" />
    </el-form-item>

    <el-form-item label="活动预算" prop="cost">
      <el-input v-model="activity.cost" />
    </el-form-item>

    <el-form-item label="活动时间" prop="activityTime">
      <el-date-picker
          v-model="activity.activityTime"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>

    <el-form-item label="活动描述" prop="description">
      <el-input v-model="activity.description" type="textarea"
                maxlength="255" minlength="3" show-word-limit rows="6"/>
    </el-form-item>


    <el-form-item label=" ">
      <el-button type="primary" @click="submit(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      <el-button @click="router.back()">返回</el-button>
    </el-form-item>

  </el-form>
</template>

<style scoped>

</style>